<template>
  <div class="file-content-layout">
    <header-view>
      <img src="../../../assets/image/back.png" alt="" class="icon" @click="goBack">
      <div class="title">{{info.name.replace('.' + info.suffix, '')}}</div>
      <div class="icon"></div>
    </header-view>
    <div class="content">
      <!--图片展示-->
      <img v-if="info.suffix.includes('png') ||info.suffix.includes('jpg')"
           :src="ServerUrl + '/file/download?id=' + info.id"
      >
      <!--文档文件-->
      <div id="pdf"
           v-touch:scaleTouch = "{func: scalePic, param: ''}"
           v-touch:slideTouch = "{func: movePic, param: ''}"
           v-if="info.suffix === 'pdf'|| info.suffix === 'doc' || info.suffix === 'docx'|| info.suffix === 'xlsx'|| info.suffix === 'xls'">
        <pdf
            v-for="i in numPages"
            :key="i"
            :src="pdfSrc"
            :page="i"
        >
        </pdf>
      </div>
      <tinymce
          v-if="info.suffix === 'html'"
          ref="tinymce"
          :selected-file="info"
          :toolbar="toolbar"
          @onClick="onClick"
          :readonly="readonly"
          :is-update="isUpdate"
      />
      <!--无内容-->
      <img v-if="info.suffix === ''" src="../../../assets/image/folder.png" alt>
    </div>
  </div>
</template>

<script>
import HeaderView from '../../common/HeaderView';
import pdf from 'vue-pdf'
import tinymce from '../../common/tinymce'

import { getFileDetails, updateHtml } from '../../../api/file'

export default {
  name: 'FileContentView',
  components: { HeaderView, pdf, tinymce },
  directives: {
    touch: {
      bind: function bind(el, binding, vnode) {
        console.log(vnode)
        let type = binding.arg; // 传入点击的类型
        let coordinate = {}; // 记录坐标点的对象
        let timeOutTap = void 0;
        let timeOutLong = void 0;
        let scaleSize = void 0; // 缩放尺寸
        let displacement = {}; //移动的位移
        // 勾股定理计算距离
        function getDistance(bg, end) {
          return Math.sqrt(Math.pow(end.x - bg.x, 2) + Math.pow(end.y - bg.y, 2));
        }
        // 点击开始的时候
        el.addEventListener('touchstart', function (e) {
          // 获取第一个手指点击的坐标
          let x = e.touches[0].pageX;
          let y = e.touches[0].pageY;
          console.log(x,y)
          // 如果点击的时间很长，那么点击的类型就是长按 --- longTouch
          timeOutLong = setTimeout(function () {
            timeOutLong = 0;
            if (type === 'longTouch') {
              binding.value.func(binding.value.param);
            }
          }, 2000);
          timeOutTap = setTimeout(function () {
            timeOutTap = 0;
            if (type === 'tap' && e.touches.length === 1) {
              binding.value.func(binding.value.param);
            }
          }, 200);
          // 如果是两个手指，而且类型是缩放 --- scaleTocuh
          if (e.touches.length > 1 && type === 'scaleTouch') {
            // 记录双指的间距长度
            coordinate.start = getDistance({
              x: e.touches[0].pageX,
              y: e.touches[0].pageY
            }, {
              x: e.touches[1].pageX,
              y: e.touches[1].pageY
            });
          }
          // 如果是移动的话，还要记录下来最开始的位置,只能一个手指位移
          if (type === 'slideTouch' && e.touches.length === 1) {
            // debugger
            displacement.start = {
              x: e.touches[0].pageX,
              y: e.touches[0].pageY
            };
          }
        }, false);

        el.addEventListener('touchmove', function (e) {
          clearTimeout(timeOutTap);
          clearTimeout(timeOutLong);
          timeOutTap = 0;timeOutLong = 0;
          // 如果是缩放类型
          if (type === 'scaleTouch' && e.touches.length === 2) {
            // 计算移动过程中的两个手指的距离
            coordinate.stop = getDistance({
              x: e.touches[0].pageX,
              y: e.touches[0].pageY
            }, {
              x: e.touches[1].pageX,
              y: e.touches[1].pageY
            });
            // 设置缩放尺寸
            scaleSize = coordinate.stop / coordinate.start - 1;
            // 这里设置图片不能无限放大与缩小
            // 这里设置放大缩小速度慢一点，所以 /4一下
            binding.value.func(scaleSize / 2, false);
          }
          // 如果是移动类型
          if (type === 'slideTouch' && e.touches.length === 1) {
            displacement.end = {
              x: e.changedTouches[0].pageX,
              y: e.changedTouches[0].pageY
            };
            binding.value.func({ x: displacement.end.x - displacement.start.x, y: displacement.end.y - displacement.start.y, is_endMove: false });
          }
        }, false);

        el.addEventListener('touchend', function (e) {
          console.log(e)
          if (type === 'scaleTouch') {
            binding.value.func(0, true);
          }
          if (type === 'slideTouch') {
            binding.value.func({ x: 0, y: 0, is_endMove: true });
          }
        }, false);
      }
    }
  },
  data() {
    return {
      info: this.$route.params.info,
      content: '',
      ServerUrl: process.env.VUE_APP_BASE_API,
      pdfSrc: '',
      numPages: undefined,
      readonly: true,
      toolbar: '',
      bodyWidth: document.body.clientWidth,
      ele: null, // 不能在这里设置， dom还没有生成
      isUpdate: 1,
    }
  },
  mounted() {
    // console.log(this.info)
    this.ele = document.getElementById('pdf')
    this.pdfSrc = this.ServerUrl + '/file/export/pdf?fileid=' + this.info.id + '#toolbar=0'
    console.log(this.pdfSrc)
    if(this.info.suffix === 'html')
      this.getFileDetails()
    if(this.info.suffix === 'pdf'|| this.info.suffix === 'doc' || this.info.suffix === 'docx'|| this.info.suffix === 'xlsx'|| this.info.suffix === 'xls')
      this.getNumPages()
    this.getEditAuthority()
  },
  methods: {
    getEditAuthority(){
      const realname = JSON.parse(localStorage.getItem('userInfo')).realName
      const editor = this.info.editor
      if (this.info.suffix.includes('html')) {
        if (editor === realname) {
          this.$store.commit('index/set_authority', {
            isLook: 1,
            isUpdate: 1,
            isDelete: 0
          })
          this.readonly = false
          this.isUpdate = 1
          this.toolbar = 'undo redo | bold italic forecolor backcolor | lists image media | removeformat restoredraft save'
        } else {
          this.readonly = true
          this.toolbar = ''
          if (editor) {
            this.$toast(
                `文档正由${editor}编辑，请联系他释放权限后，您才能编辑`
            )
          }
          this.$store.commit('index/set_authority', {
            isLook: 1,
            isUpdate: 0,
            isDelete: 0
          })
        }
      }
    },
    getNumPages() {
      // console.log(this.pdfSrc)
      this.$loading.show();
      let loadingTask = pdf.createLoadingTask(this.pdfSrc)
      loadingTask.promise.then(pdf => {
        console.log(pdf)
        this.numPages = pdf.numPages
        this.$loading.hide();
      }).catch(err => {
        console.error('pdf 加载失败', err);
      })
    },
    goBack() {
      if(this.$route.params.type === 'file')
        this.$router.go(-1);
      else if (this.$route.params.type === 'share')
        this.$router.push({name: 'index', params: {index: 3}})
    },
    getFileDetails() {
      sessionStorage.fileid = this.info.id
      getFileDetails(this.info.id)
          .then(result => {
            // console.log(result)
            const rx = /<body[^>]*>([\s\S]+?)<\/body>/i
            const m = rx.exec(result)
            let c1 = m[1].replace(/<img width="100%"/g, "<img");
            let c2 = c1.replace(/<img/g, '<img width="100%" height="auto"');
            // this.content = m[1];
            this.$refs.tinymce.myValue = c2;
            this.$refs.tinymce.oldValue = c2;
          })
          .catch(err => {
            console.log(err)
          })
    },
    onClick() {
      console.log(123)
    },
    updateHtml() {
      const fileid = this.info.id
      const html = this.$refs.tinymce.getHtml()
      updateHtml(fileid, html)
          .then(result => {
            console.log(result)
          })
          .catch(err => {
            console.log(err)
          })
    },
    //缩放
    scalePic: function(param, is_endScale){
      let nodeStyle = this.ele.style.transform;
      let changeSize = nodeStyle ?  parseFloat(nodeStyle.slice(nodeStyle.indexOf('scale')+6)) : 0;
      if(is_endScale){
        // 缩放图片结束，要重新计算定位
        this.setMaxdisp(changeSize,parseInt(this.ele.style.marginLeft), parseInt(this.ele.style.marginTop), 'scale')
        return
      }
      if(nodeStyle){
        // 如果存在的话，就说明已经设置了，scale已经改变了
        let currScaleSize = changeSize + param;
        currScaleSize > 3 ? currScaleSize = 3 : null
        currScaleSize < 1 ? currScaleSize = 1 : null
        this.ele.style.transform = 'translate(-50%, -50%) scale('+currScaleSize+','+currScaleSize+')';
      }else{ // 如果不存在，就说明是第一次设置
        let scale = param + 1
        this.ele.style.marginLeft =  '0px';
        this.ele.style.marginTop  = '0px';
        this.ele.style.transform = 'translate(-50%, -50%) scale('+scale+','+scale+')';
      }
    },
    movePic: function(param){
      if(param.is_endMove){ // 每次移动松开手指的时候要下次移动的基础坐标
        this.baseLeft = parseInt(this.ele.style.marginLeft.slice(0, -2));
        this.baseTop = parseInt(this.ele.style.marginTop.slice(0, -2));
      }else{
        let nodeStyle = this.ele.style.transform
        if(nodeStyle){ // 有这个就表示应该是移动
          let currScaleSize = parseFloat(nodeStyle.slice(nodeStyle.indexOf('scale')+6))
          this.setMaxdisp(currScaleSize,this.baseLeft+ param.x, this.baseTop + param.y, 'move')
        }
      }
    },
    setMaxdisp:function(changeSize, changeX, changeY, type){
      // 计算最大位移
      let picHeight =  this.bodyWidth  / (this.ele.naturalWidth / this.ele.naturalHeight);
      let maxTop = ( picHeight * changeSize - window.innerHeight) /2
      let maxLeft = this.bodyWidth / 2 * (changeSize - 1)
      if(changeX >= maxLeft){
        this.ele.style.marginLeft = maxLeft + 'px'
      }else if(changeX < -maxLeft){
        this.ele.style.marginLeft = -maxLeft + 'px'
      }else if(type==='move'){
        this.ele.style.marginLeft =changeX +'px';
      }
      // 如果图片当前尺寸大于屏幕尺寸，可以移动
      if(maxTop > 0){
        if(changeY >= maxTop){
          this.ele.style.marginTop = maxTop + 'px';
        }else if(changeY < -maxTop){
          this.ele.style.marginTop = -maxTop + 'px'
        }else if(type==='move'){
          this.ele.style.marginTop = changeY+'px';
        }
      }else if(type==='move'){
        this.ele.style.marginTop = 0 +'px';
      }
    },
  }

}
</script>

<style scoped>

.title {
  flex: 1;
}
.content {
  /*background: #dcdcdc;*/
  /*min-height: 100vh;*/
  /*overflow-y: scroll;*/
  margin-top: 135px;
}
.detail {
  padding: 20px;
}

img {
  max-width: 100% !important;
  height: auto !important;
  display: block !important;
}
#pdf {
  width: 100%;
  height: 100vh;
  overflow-x: hidden;
}
</style>